/**
 * 
 */
package fr.sii.android.accessibility;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.resting.Resting;
import com.google.resting.component.impl.ServiceResponse;

import android.os.AsyncTask;
import android.util.Log;
import fr.sii.android.accessibility.model.MapEntry;

/**
 * @author LoLo
 * 
 */
public class DownloadTask extends AsyncTask<String, Void, List<MapEntry>> {

	private static final String TAG = DownloadTask.class.getSimpleName();
	
	public interface DownloadTaskCallbacks {
		void downloadFinished(List<MapEntry> mapEntries);
		void downloadError(String message);
	};

	private DownloadTaskCallbacks mCallback;

	public DownloadTask(DownloadTaskCallbacks callback) {
		mCallback = callback;
	}

	public static List<MapEntry> callWebService(String q) throws ParserConfigurationException,
			SAXException, IOException {
		
		List<MapEntry> mapEntries = new ArrayList<MapEntry>();
		
		ServiceResponse response = Resting.get("http://www.serveravip-test.appspot.com/ServerAvip", 80);

		/**************** PARSER AVEC DOM ****************************/

		if (response != null) {
			// /Le fichier Xml en string
			String xml = response.getResponseString();
			// System.out.print(xml);
			Log.d(TAG, xml);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(new StringReader(xml)));
			// normalize the document
			doc.getDocumentElement().normalize();
			// get the root node
			NodeList nodeList = doc.getElementsByTagName("map");
			final int length = nodeList.getLength();
			for (int j = 0; j < length; ++j) {
				MapEntry map = new MapEntry();
				Node node = nodeList.item(j);
				// the node has three child nodes
				for (int i = 0; i < node.getChildNodes().getLength(); i++) {
					Node temp = node.getChildNodes().item(i);
					if (temp.getNodeName().equalsIgnoreCase("name")) {
						map.name = temp.getTextContent();
					} else if (temp.getNodeName().equalsIgnoreCase("lat")) {
						map.lat = temp.getTextContent();
					} else if (temp.getNodeName().equalsIgnoreCase("lon")) {
						map.lon = temp.getTextContent();
					} else if (temp.getNodeName().equalsIgnoreCase("url")) {
						map.url = temp.getTextContent();
					}
				}

				mapEntries.add(map);

				Log.d("map", "map: " + map.name + " lat: " + map.lat + " lon: "
						+ map.lon + " url: " + map.url);
			}
		}
		return mapEntries;
	} // end callWebService()

	@Override
	protected List<MapEntry> doInBackground(String... url) {
		try {
			if (url.length == 1) {
				List<MapEntry> mapEntries = callWebService(url[0]);
				return mapEntries;
			} else {
				String message = "Incorrect number of parameters for "+TAG + ": "+url.length;
				throw new IllegalArgumentException(message);
			}
		} catch (Exception e) {
			if (mCallback != null) {
				mCallback.downloadError(e.getMessage());
			}
			return new ArrayList<MapEntry>(0);
		}
	}

	@Override
	protected void onPostExecute(List<MapEntry> result) {
		super.onPostExecute(result);

		if (mCallback != null) {
			mCallback.downloadFinished(result);
		}
	}

}
